from django.db.models import Q
from django.http import Http404
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ViewSet

from scan.models import Machine, Account
from scan.serializers import MachineSerializer, AccountSerializer
from sdk.ali.ecs import AliEcs
from tools.viewsets import CustomPageViewSet, StandardPagination, CustomViewSet


class MachineViewSet(CustomPageViewSet):
    # 用一个视图集替代MachineList和MachineDetail两个视图
    serializer_class = MachineSerializer
    pagination_class = StandardPagination

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            # 查询的高阶操作:或者的关系
            return Machine.objects.filter(
                Q(InstanceId__contains=keyword) |
                Q(Description__contains=keyword) |
                Q(HostName__in=keyword)).all()
        return Machine.objects.all()


class AccountViewSet(CustomViewSet):
    # 用一个视图集替代MachineList和MachineDetail两个视图
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    pagination_class = StandardPagination

    def retrieve(self, request, *args, **kwargs):
        """查看加密数据详情页事，需要解密"""
        response = super(AccountViewSet, self).retrieve(request, *args, **kwargs)
        response.data['Password'] = response.data['Password'].replace('---', '')
        return Response(response.data)


class MachineStatusAPIView(ViewSet):
    def get_instance(self, InstanceId):
        """根据传入的instanceid获取机器实例"""
        try:
            return Machine.objects.get(InstanceId=InstanceId)
        except Machine.DoesNotExist:
            return Http404

    @action(detail=True, methods=['get'])
    def start(self, request, pk):
        """启动阿里云主机"""
        instance = self.get_instance(pk)
        if instance.Status == 'Running':
            return Response({'code': 200, 'msg': '当前机器已开启，无需再次开启'})
        response = AliEcs().start(InstanceId=instance.InstanceId)
        if not response:
            return Response({'code': 500, 'msg': '开机失败'})
        instance.Status = 'Running'
        instance.save()
        return Response({'code': 200, 'msg': '开机成功'})

    @action(detail=True)
    def stop(self, request, pk):
        """关闭阿里云主机"""
        instance = self.get_instance(pk)
        if instance.Status == 'Stopped':
            return Response({'code': 200, 'msg': '当前机器已关机，无需再次关机'})
        response = AliEcs().stop(InstanceId=instance.InstanceId)
        if not response:
            return Response({'code': 500, 'msg': '关机失败'})
        instance.Status = 'Stopped'
        return Response({'code': 200, 'msg': '关机成功'})

    @action(detail=True)
    def reboot(self, request, pk):
        """重启阿里云主机"""
        instance = self.get_instance(pk)
        AliEcs().reboot(InstanceId=instance.InstanceId)
        return Response({'code': 200, 'msg': '重启成功'})

    @action(detail=True, methods=['post'])
    def reset_password(self, request, pk):
        """重置阿里云账号密码"""
        password = request.data.get('password')
        instance = self.get_instance(pk)

        response = AliEcs().set_password(InstanceId=instance.InstanceId, Password=password)
        if not response:
            return Response({'code': 200, 'msg': '重置密码失败'})
        account = instance.accounts.filter(User='root').first()
        account.Password = password
        account.save()
        return Response({'code': 200, 'msg': '重置密码成功,请重启后密码生效'})
